import * as types from '../types';
import * as utils from '../../utils/helps';
import api from 'api';
import app from './app';
import dataManager from '../../utils/dataManager';

const chart = {
  state: {
    // 存储组件所有的配置，以id为key
    controls: {},
    // 当前选中组件的id
    currentId: '',
    removeSublayers: {},
  },
  getters: {
    controls: state => utils.integrationControl(state.controls),
    currentId: state => state.currentId,
    currentControl: state => utils.deepCopy(state.controls[state.currentId]),
    removeSublayers: state => state.removeSublayers,
  },
  mutations: {
    // 更新图表配置
    [types.UPDATE_CHART_CONFIG](state, { data, isAllUpdata }) {
      if (data) {
        let controlData;
        if (isAllUpdata) {
          controlData = utils.setAppData(JSON.parse(data));
          state.controls = Object.assign({}, controlData);
        } else {
          //TODO: 增加/删除组件时要注意更改app modules
          controlData = utils.setAppData(data);
          state.controls = Object.assign({}, state.controls, controlData);
        }
      }
    },
    // 存储当前组件id
    [types.UPDATA_APPLY_CURRENTID](state, id) {
      state.currentId = id;
    },
    // 储存删除专题图层的信息
    [types.DELETE_SUBJECTLAYER_DATA](state, sublayerData) {
      state.removeSublayers = sublayerData;
    },
  },
  actions: {
    // 查询应用的详细信息
    async [types.GET_APP_DATA]({ commit }, id) {
      const response = await api.datav.findAppById({ id });
      if (response.data.data === '') {
        const ids = Object.keys(JSON.parse(response.data.info));
        commit(types.UPDATA_APP_COMPONENTS, { ids, firstUpdate: true });
        commit(types.UPDATA_APP_DATA, {
          id: response.data.id,
          name: response.data.name,
        });
        commit(types.UPDATE_CHART_CONFIG, {
          data: response.data.info,
          isAllUpdata: true,
        });
        return response.data;
      } else {
        return false;
      }
    },
  },
};
export default chart;
